package com.cskaoyan.service;

import com.cskaoyan.bean.Storage;
import com.cskaoyan.bean.StorageExample;
import com.cskaoyan.mapper.*;
import com.cskaoyan.utils.DateUtils;
import com.cskaoyan.vo.StorageListVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class StorageServiceImpl implements StorageService {

    @Autowired
    StorageMapper storageMapper;

    @Value("${img.localPath}")
    String localPath;    //本地路径
    @Value("${img.accessPath}")
    String accessPath;   //访问路径

    /**
     * 作者：grz
     * 功能：新增图片
     */
    @Override
    public Storage insertStorage(MultipartFile file) throws IOException {
        //获取图片大小
        int size = (int) file.getSize();
        //获取图片名称
        String name = file.getOriginalFilename();
        //获取图片类型
        String type = file.getContentType();
        //获取文件类型后缀
        String suffixName = file.getOriginalFilename();
        String suffix = "";
        if (suffixName != null) {
            int indexOf = suffixName.lastIndexOf(".");
            suffix = suffixName.substring(indexOf + 1);
        }
        UUID uuid = UUID.randomUUID();
        String simpleUUID = uuid.toString().replace("-", "");
        //获取日期
        String timeString = DateUtils.getCurrentTimeString();
        String key = simpleUUID + "_" + timeString + "." + suffix;

        //创建文件对象
        File targetFile = new File(localPath, key);
        if (!targetFile.getParentFile().exists()) {
            boolean mkdirs = targetFile.getParentFile().mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("Storage图片保存失败");
            }
        }
        file.transferTo(targetFile);
        String url = accessPath + key;
        Storage storage = new Storage(null, key, name, type, size, url, new Date(), new Date(), false);
        //插入数据
        storageMapper.insert(storage);
        return storage;
    }

    /**
     * 作者：grz
     * 功能：获取图片列表
     */
    @Override
    public StorageListVo list(Integer page, Integer limit, String sort, String order, String key, String name) {

        PageHelper.startPage(page, limit);

        StorageExample storageExample = new StorageExample();
        storageExample.setOrderByClause(sort + " " + order);
        StorageExample.Criteria criteria = storageExample.createCriteria();
        //模糊查询条件
        if (key != null) {
            criteria.andKeyEqualTo("%" + key + "%");
        }
        if (name != null) {
            criteria.andNameEqualTo("%" + name + "%");
        }
        //只查询未删除的图片
        criteria.andDeletedEqualTo(false);
        List<Storage> storageList = storageMapper.selectByExample(storageExample);

        //通过PageInfo获取分页信息
        PageInfo<Storage> goodsPageInfo = new PageInfo<>(storageList);
        long total = goodsPageInfo.getTotal();

        StorageListVo storageListVo = new StorageListVo();
        storageListVo.setTotal(total);
        storageListVo.setItems(storageList);
        return storageListVo;
    }

    /**
     * 作者：grz
     * 功能：删除图片以及其他表中的图片信息
     */
    @Override
    public int delete(Storage storage) {

        storage.setDeleted(true);
        int i = storageMapper.updateByPrimaryKey(storage);

        //拿到图片key，删除所有的相关图片
        String key = storage.getKey();

        //删除的图片替代
        File file = new File(localPath + "\\" + key);
        File deleteImg = new File(localPath + "\\delete\\delete.png");

        //写入图片
        byte[] b = new byte[(int) deleteImg.length()];
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream(deleteImg);
            //没有指定文件则会创建
            out = new FileOutputStream(file);
            //read()--int，-1表示读取完毕
            while (in.read(b) != -1) {
                out.write(b);
            }
            out.flush();
            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (i <= 0) {
            return 404;
        }
        return 200;
    }

    @Override
    public int update(Storage storage) {

        int i = storageMapper.updateByPrimaryKey(storage);
        if (i <= 0) {
            return 404;
        }
        return 200;
    }
}










